package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Wxblqsensor;
import com.example.onlinemonitoring.model.Wxblqhistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.serviceImpl.WxblqsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.text.ParseException;
import java.util.Date;
import com.example.onlinemonitoring.Util.CRC16;

import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.DelayQueue;
/*这里beanName需要和数据库Appdevice中的simple对应并加上Com,不对应请自行修改
    例:simple:dlhl
    @Service("dlhlCom")
*/
@Service("wxblqCom")
@Scope("prototype")
public class WxblqCom extends CommPortManager {
    private int nextstep = 1;// 轮询阶段
    Integer addrindex = 0;// 避雷器轮询地址
    private static final int DELAY5 = 0;// 等待
    private static final int BRO = 1;// 唤醒
    private static final int BLQ = 2;
    private static final int PT = 3;
    private static final int WSD = 4;
    public int currblqaddr;// 当前询问的避雷器地址
    int numindex = 0;
    Date dt = new Date();// 一帧数据的广播时间
    private short BLQReSend[] = new short[10000];// 监测避雷器通讯是否正常的指标
    private short PtReSend[] = new short[10000];// 监测母线通讯是否正常的指标
    private short WSDReSend[] = new short[10000];// 监测温湿度通讯是否正常的指标
    private Wxblqsensor sender = new Wxblqsensor();
    private boolean pt;
    private boolean wsd;
    @Autowired
    private WxblqsensorServiceImpl wxblqsensorServiceImpl;

    @Override
    public void receiveData(String str) {
        str = str.toUpperCase();
        setText(str);
        if (dt == null) {
            dt = new Date();
        }

        if (str.substring(2, 4).equals("04")) {
            WSDReSend[currblqaddr] = 0;
            nextstep = BLQ;
            int dataStype = 1, status = 0;
            int addr = parseHex4(str.substring(0, 2));
            float temperatrue, humiDity;
            int temp = parseHex4(str.substring(6, 10));
            int humidity = parseHex4(str.substring(10, 14));
            temperatrue = (float) temp / 10;
            humiDity = (float) humidity / 10;
            SensorWSDData(ad.getStationid(), addr, temperatrue, humiDity, dataStype, status);
        } else {
            int status = 0;
            String blqtip;
            if (str.length() > 6) {
                blqtip = str.substring(6, 8);
            } else {
                return;
            }
            System.out.println("=================================避雷器=======================================" + blqtip);
            int dataStype = 0;
            int addr = parseHex4(str.substring(8, 12));
            if (blqtip.equals("A3"))// 有雷击放电时主动上送
            {
                int i = 0;
                while((i = str.indexOf("FF5510A3"))!=-1){
                    lj(str.substring(i,i+20));
                    str = str.substring(i+20);
                }
            }
            if (blqtip.equals("A6")) {
                float LastVref = 0;
                float LastAcurrentAngle = 0, LastBcurrentAngle = 0, LastCcurrentAngle = 0;
                float LastAWcurrent = 0, LastBWcurrent = 0, LastCWcurrent = 0;
                float LastACurrent = 0, LastBCurrent = 0, LastCCurrent = 0;
                float LastAAngle = 0, LastBAngle = 0, LastCAngle = 0;
                float LastBatteryVoltage = 0, LastChargeVoltage = 0, LastCurrentFrequency = 0;
                float LastACurrentGear = 0, LastBCurrentGear = 0, LastCCurrentGear = 0;
                float LastRefVoltageGear = 0, LastCurrentVectorSum = 0, LastVectorAngle = 0;
                byte[] mybyte_Vref = HexUtil.hexString2Bytes(str.substring(12, 20));
                LastVref = HexUtil.byte2float(mybyte_Vref);
                byte[] mybyte_ACurrent = HexUtil.hexString2Bytes(str.substring(20, 28));
                LastACurrent = HexUtil.byte2float(mybyte_ACurrent);
                byte[] mybyte_BCurrent = HexUtil.hexString2Bytes(str.substring(28, 36));
                LastBCurrent = HexUtil.byte2float(mybyte_BCurrent);
                byte[] mybyte_CCurrent = HexUtil.hexString2Bytes(str.substring(36, 44));
                LastCCurrent = HexUtil.byte2float(mybyte_CCurrent);
                byte[] mybyte_AAngle = HexUtil.hexString2Bytes(str.substring(44, 52));
                LastAAngle = HexUtil.byte2float(mybyte_AAngle);
                byte[] mybyte_BAngle = HexUtil.hexString2Bytes(str.substring(52, 60));
                LastBAngle = HexUtil.byte2float(mybyte_BAngle);
                byte[] mybyte_CAngle = HexUtil.hexString2Bytes(str.substring(60, 68));
                LastCAngle = HexUtil.byte2float(mybyte_CAngle);
                byte[] mybyte_BatteryVoltage = HexUtil.hexString2Bytes(str.substring(68, 76));
                LastBatteryVoltage = HexUtil.byte2float(mybyte_BatteryVoltage);
                byte[] mybyte_ChargeVoltage = HexUtil.hexString2Bytes(str.substring(76, 84));
                LastChargeVoltage = HexUtil.byte2float(mybyte_ChargeVoltage);
                byte[] mybyte_CurrentFrequency = HexUtil.hexString2Bytes(str.substring(84, 90));
                LastCurrentFrequency = HexUtil.byte2float(mybyte_CurrentFrequency);
                LastACurrentGear = parseHex4(str.substring(90, 92));
                LastBCurrentGear = parseHex4(str.substring(92, 94));
                LastCCurrentGear = parseHex4(str.substring(94, 96));
                LastRefVoltageGear = parseHex4(str.substring(98, 100));
                LastCurrentVectorSum = parseHex4(str.substring(102, 104));
                byte[] mybyte_VectorAngle = HexUtil.hexString2Bytes(str.substring(108, 116));
                LastVectorAngle = HexUtil.byte2float(mybyte_VectorAngle);
                // 电流相角
                LastAcurrentAngle = LastAAngle;
                LastBcurrentAngle = LastBAngle;
                LastCcurrentAngle = LastCAngle;
                // 全电流
                LastAWcurrent = LastACurrent;
                LastBWcurrent = LastBCurrent;
                LastCWcurrent = LastCCurrent;

                if (addr > 8000) {// 避雷器数据
                    BLQReSend[currblqaddr] = 0;
                    if (pt)
                        nextstep = PT;
                    else if (wsd)
                        nextstep = WSD;
                    else
                        nextstep = DELAY5;
                    SensorData(ad.getStationid(), addr, LastVref, LastACurrent, LastBCurrent, LastCCurrent, LastAAngle,
                            LastBAngle,
                            LastCAngle, LastBatteryVoltage, LastChargeVoltage, LastCurrentFrequency, LastACurrentGear,
                            LastBCurrentGear, LastCCurrentGear, LastRefVoltageGear, LastCurrentVectorSum,
                            LastVectorAngle, LastAcurrentAngle, LastBcurrentAngle, LastCcurrentAngle, LastAWcurrent,
                            LastBWcurrent, LastCWcurrent);
                } else {// 母线数据
                    PtReSend[currblqaddr] = 0;
                    if (wsd)
                        nextstep = WSD;
                    else
                        nextstep = BLQ;
                    SensorPTData(ad.getStationid(), addr, LastVref, LastACurrent, LastBCurrent, LastCCurrent);
                }
                setText(addr + " " + LastACurrent + " " + LastVref + " ");
            }
        }

        if (nextstep == DELAY5) {
            Wxblqsensor blq = new Wxblqsensor();
            blq.setDeviceaddr(currblqaddr);
            blq.setStationid(ad.getStationid());
            blq.setDevicegroup(ad.getDevicegroup());
            blq = wxblqsensorServiceImpl.getModel(blq);
            blq.setLastdatatime(new Date());
            // blq.setLastalarmlevel(HexUtil.MAX(
            //         new int[] { HexUtil.isnull(blq.getLastalarmlevelBlq()), HexUtil.isnull(blq.getLastalarmlevelPt()),
            //                 HexUtil.isnull(blq.getLastalarmlevelLj()), HexUtil.isnull(blq.getLastalarmlevelWsd()) }));
            // blq.setLastalarmmessage(blq.getLastalarmmessageBlq() + blq.getLastalarmmessagePt()
            //         + blq.getLastalarmmessageLj() + blq.getLastalarmmessageWsd());
           // blq.setLasthisdatatime(addHistory(blq)); 
           addHistory(blq);
                if ( wxblqsensorServiceImpl.Update(blq, false) == 0) {
                setText("更新实时数据失败，请检查数据库连接");
            }

        }
    }
 private void SensorPTData(int stationid, int addr, float LastVref, float LastAVoltage, float LastBVoltage,
            float LastCVoltage) {
        String str = "";
        float avVref = 0, avACurrent = 0, avBCurrent = 0, avCCurrent = 0;
        Wxblqsensor ptblq = new Wxblqsensor();
        ptblq.setPtaddr(addr);
        ptblq.setDevicegroup(ad.getDevicegroup());
        ptblq.setStationid(ad.getStationid());
        List<Wxblqsensor> ptlist = wxblqsensorServiceImpl.getPtModel(ptblq);
        if (ptlist.size() == 0) {
            setText("当前数据库无母线监测点：" + addr + " ！ 请先添加该监测点！");
            return;
        } else {
            ptblq = ptlist.get(0);
        }

        ptblq.setLastcommunicationstatusPt(0);
        ptblq.setLastdatatime(dt);
        float ptxishu = nto(ptblq.getPtxishuconfig());
        LastVref *= ptxishu;
        LastAVoltage *= ptxishu;
        LastBVoltage *= ptxishu;
        LastCVoltage *= ptxishu;

        if (numindex < 1) {
            ptblq.setLastvref(LastVref);
            ptblq.setLastavoltage(LastAVoltage);
            ptblq.setLastbvoltage(LastBVoltage);
            ptblq.setLastcvoltage(LastCVoltage);
            avVref = LastVref;
            avACurrent = LastAVoltage;
            avBCurrent = LastBVoltage;
            avCCurrent = LastCVoltage;
            ptblq.setAvvref(avVref);
            ptblq.setLastavacurrent(avACurrent);
            ptblq.setLastavbcurrent(avBCurrent);
            ptblq.setLastavccurrent(avCCurrent);
            str = "解析日新无线避雷器PT数据：";
            str = str + "站点号：" + stationid;
            str = str + "设备地址：" + addr + "\r\n";
            str = str + "A相基波有效值：" + float2(LastAVoltage) + "V   ";
            str = str + "B相基波有效值：" + float2(LastBVoltage) + "V   ";
            str = str + "C相基波有效值：" + float2(LastCVoltage) + "V   ";
            setText(str);
            numindex++;
        }
        Wxblqhistory pthis = new Wxblqhistory();
        pthis.setDeviceaddr(addr);
        pthis.setVref(LastVref);
        pthis.setAvoltage(LastAVoltage);
        pthis.setBvoltage(LastBVoltage);
        pthis.setCvoltage(LastCVoltage);
        List<Wxblqhistory> pthislist = wxblqsensorServiceImpl.getRecent6Data(pthis);
        Random random = new Random();
        if (pthislist.size() >= 6) {
            pthislist.remove(0);
            pthislist.add(pthis);
            Wxblqhistory avhis = new Wxblqhistory();
            avhis = getAverage(pthislist);
            avACurrent = avhis.getAvoltage();
            avBCurrent = avhis.getBvoltage();
            avCCurrent = avhis.getCvoltage();
            str = "解析日新无线避雷器PT数据：";
            str = str + "站点号：" + stationid;
            str = str + "设备地址：" + addr + "\r\n";
            str = str + "A相基波有效值:" + float2(avhis.getAvoltage()) + "V    ";
            str = str + "B相基波有效值：" + float2(avhis.getBvoltage()) + "V    ";
            str = str + "C相基波有效值：" + float2(avhis.getCvoltage()) + "V\r\n";
            str = str + "A相实时:" + float2(LastAVoltage) + "V    ";
            str = str + "B相实时：" + float2(LastBVoltage) + "V    ";
            str = str + "C相实时：" + float2(LastCVoltage) + "V    ";
            
            float simFrequ = 50;
            float AsimxbVol = avACurrent, AsimxbVol1 = avACurrent, AsimxbVol2 = avACurrent, AsimxbVol3 = avACurrent,
                    BsimxbVol = avBCurrent, BsimxbVol1 = avBCurrent, BsimxbVol2 = avBCurrent, BsimxbVol3 = avBCurrent,
                    CsimxbVol = avCCurrent, CsimxbVol1 = avCCurrent, CsimxbVol2 = avCCurrent, CsimxbVol3 = avCCurrent;
            if (avACurrent > 5 || avBCurrent > 5 || avCCurrent > 5) {
                simFrequ += (float) 0.01 * (random.nextInt(3) - 1);
            } else {
                simFrequ = 0;
            }

            ptblq.setSimfrequence(simFrequ);
            str += "系统频率：" + simFrequ + "Hz\r\n";
            AsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
            AsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
            AsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
            AsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
            str += "A相3次谐波电压：" + float2(AsimxbVol) + "V\r\n";
            str += "A相5次谐波电压：" + float2(AsimxbVol1) + "V\r\n";
            str += "A相7次谐波电压：" + float2(AsimxbVol2) + "V\r\n";
            str += "A相9次谐波电压：" + float2(AsimxbVol3) + "V\r\n";
            BsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
            BsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
            BsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
            BsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
            str += "B相3次谐波电压：" + float2(BsimxbVol) + "V\r\n";
            str += "B相5次谐波电压：" + float2(BsimxbVol1) + "V\r\n";
            str += "B相7次谐波电压：" + float2(BsimxbVol2) + "V\r\n";
            str += "B相9次谐波电压：" + float2(BsimxbVol3) + "V\r\n";
            CsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
            CsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
            CsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
            CsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
            str += "C相3次谐波电压：" + float2(CsimxbVol) + "V\r\n";
            str += "C相5次谐波电压：" + float2(CsimxbVol1) + "V\r\n";
            str += "C相7次谐波电压：" + float2(CsimxbVol2) + "V\r\n";
            str += "C相9次谐波电压：" + float2(CsimxbVol3) + "V\r\n";
            ptblq.setAsimxbvoltage(AsimxbVol);
            ptblq.setAsimxbvoltage1(AsimxbVol1);
            ptblq.setAsimxbvoltage2(AsimxbVol2);
            ptblq.setAsimxbvoltage3(AsimxbVol3);
            ptblq.setBsimxbvoltage(BsimxbVol);
            ptblq.setBsimxbvoltage1(BsimxbVol1);
            ptblq.setBsimxbvoltage2(BsimxbVol2);
            ptblq.setBsimxbvoltage3(BsimxbVol3);
            ptblq.setCsimxbvoltage(CsimxbVol);
            ptblq.setCsimxbvoltage1(CsimxbVol1);
            ptblq.setCsimxbvoltage2(CsimxbVol2);
            ptblq.setCsimxbvoltage3(CsimxbVol3);
            setText(str + "\r\n");
            ptblq.setLastvref(LastVref);
            ptblq.setLastavoltage(LastAVoltage);
            ptblq.setLastbvoltage(LastBVoltage);
            ptblq.setLastcvoltage(LastCVoltage);
            ptblq.setAvvref(avVref);
            ptblq.setLastavacurrent(avACurrent);
            ptblq.setLastavbcurrent(avBCurrent);
            ptblq.setLastavccurrent(avCCurrent);
        } else {
            if (numindex > 1) {
                str = "解析日新无线避雷器PT数据：";
                str = str + "站点号：" + stationid;
                str = str + "设备地址：" + addr + "\r\n";
                str = str + "A相基波有效值:" + float2(LastAVoltage) + "V\r\n";
                str = str + "B相基波有效值：" + float2(LastBVoltage) + "V\r\n";
                str = str + "C相基波有效值：" + float2(LastCVoltage) + "V\r\n";
                float simFrequ = 50;
                float AsimxbVol = LastAVoltage, AsimxbVol1 = LastAVoltage, AsimxbVol2 = LastAVoltage,
                        AsimxbVol3 = LastAVoltage, BsimxbVol = LastBVoltage, BsimxbVol1 = LastBVoltage,
                        BsimxbVol2 = LastBVoltage, BsimxbVol3 = LastBVoltage, CsimxbVol = LastCVoltage,
                        CsimxbVol1 = LastCVoltage, CsimxbVol2 = LastCVoltage, CsimxbVol3 = LastCVoltage;

                if (avACurrent > 5 || avBCurrent > 5 || avCCurrent > 5) {
                    simFrequ += (float) 0.01 * (random.nextInt(3) - 1);
                } else {
                    simFrequ = 0;
                }
                ptblq.setSimfrequence(simFrequ);
                str += "系统频率：" + simFrequ + "Hz\r\n";
                AsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                AsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                AsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                AsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                str += "A相3次谐波电压：" + float2(AsimxbVol) + "V\r\n";
                str += "A相5次谐波电压：" + float2(AsimxbVol1) + "V\r\n";
                str += "A相7次谐波电压：" + float2(AsimxbVol2) + "V\r\n";
                str += "A相9次谐波电压：" + float2(AsimxbVol3) + "V\r\n";
                BsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                BsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                BsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                BsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                str += "B相3次谐波电压：" + float2(BsimxbVol) + "V\r\n";
                str += "B相5次谐波电压：" + float2(BsimxbVol1) + "V\r\n";
                str += "B相7次谐波电压：" + float2(BsimxbVol2) + "V\r\n";
                str += "B相9次谐波电压：" + float2(BsimxbVol3) + "V\r\n";
                CsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                CsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                CsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                CsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                str += "C相3次谐波电压：" + float2(CsimxbVol) + "V\r\n";
                str += "C相5次谐波电压：" + float2(CsimxbVol1) + "V\r\n";
                str += "C相7次谐波电压：" + float2(CsimxbVol2) + "V\r\n";
                str += "C相9次谐波电压：" + float2(CsimxbVol3) + "V\r\n";
                ptblq.setAsimxbvoltage(AsimxbVol);
                ptblq.setAsimxbvoltage1(AsimxbVol1);
                ptblq.setAsimxbvoltage2(AsimxbVol2);
                ptblq.setAsimxbvoltage3(AsimxbVol3);
                ptblq.setBsimxbvoltage(BsimxbVol);
                ptblq.setBsimxbvoltage1(BsimxbVol1);
                ptblq.setBsimxbvoltage2(BsimxbVol2);
                ptblq.setBsimxbvoltage3(BsimxbVol3);
                ptblq.setCsimxbvoltage(CsimxbVol);
                ptblq.setCsimxbvoltage1(CsimxbVol1);
                ptblq.setCsimxbvoltage2(CsimxbVol2);
                ptblq.setCsimxbvoltage3(CsimxbVol3);
                setText(str + "\r\n");
                ptblq.setLastvref(LastVref);
                ptblq.setLastavoltage(LastAVoltage);
                ptblq.setLastbvoltage(LastBVoltage);
                ptblq.setLastcvoltage(LastCVoltage);
                ptblq.setAvvref(avVref);
                ptblq.setLastavacurrent(LastAVoltage);
                ptblq.setLastavbcurrent(LastBVoltage);
                ptblq.setLastavccurrent(LastCVoltage);
            }
            if (numindex == 1) {
                numindex++;
            }
        }
        GetPTAlarm(ptblq);
    }
    private void GetPTAlarm(Wxblqsensor blq) {
        int alarmLevel = 0; // 报警等级
        String alarmMessage = "";// '报警消息

        blq.setLastavacurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(blq.getLastavacurrent()),
                HexUtil.isnull(blq.getAvacurrentalarmvalue()),
                HexUtil.isnull(blq.getAvacurrentalarmrelievevalue()), HexUtil.isnull(blq.getAvacurrentwarnvalue()),
                HexUtil.isnull(blq.getAvacurrentwarnrelievevalue()),
                HexUtil.isnull(blq.getLastavacurrentalarmstatus()), true, "母线A相电压",blq.getDevicegroup(), blq.getDeviceaddr(),
                blq.getPointname()));

        blq.setLastavbcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(blq.getLastavbcurrent()),
                HexUtil.isnull(blq.getAvbcurrentalarmvalue()),
                HexUtil.isnull(blq.getAvbcurrentalarmrelievevalue()), HexUtil.isnull(blq.getAvbcurrentwarnvalue()),
                HexUtil.isnull(blq.getAvbcurrentwarnrelievevalue()),
                HexUtil.isnull(blq.getLastavbcurrentalarmstatus()), true, "母线B相电压",blq.getDevicegroup(), blq.getDeviceaddr(),
                blq.getPointname()));

        blq.setLastavccurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(blq.getLastavccurrent()),
                HexUtil.isnull(blq.getAvccurrentalarmvalue()),
                HexUtil.isnull(blq.getAvccurrentalarmrelievevalue()), HexUtil.isnull(blq.getAvccurrentwarnvalue()),
                HexUtil.isnull(blq.getAvccurrentwarnrelievevalue()),
                HexUtil.isnull(blq.getLastavccurrentalarmstatus()), true, "母线C相电压",blq.getDevicegroup(), blq.getDeviceaddr(),
                blq.getPointname()));
        alarmMessage += GetAlarmMessage(blq.getLastavacurrentalarmstatus(), "母线A相电压");
        alarmMessage += GetAlarmMessage(blq.getLastavbcurrentalarmstatus(), "母线B相电压");
        alarmMessage += GetAlarmMessage(blq.getLastavccurrentalarmstatus(), "母线C相电压");

        alarmLevel = HexUtil.MAX(new int[] { blq.getLastavacurrentalarmstatus(), blq.getLastavbcurrentalarmstatus(),
                blq.getLastavccurrentalarmstatus() });
        blq.setLastalarmlevelPt(alarmLevel);
        blq.setLastalarmmessagePt(alarmMessage);
        blq.setDeviceaddr(null);
        Example example = new Example(Wxblqsensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", blq.getStationid());
        criteria.andEqualTo("devicegroup", blq.getDevicegroup());
        criteria.andEqualTo("inuse", blq.getInuse());
        criteria.andEqualTo("ptaddr", blq.getPtaddr());
        wxblqsensorServiceImpl.updateByExampleSelective(blq, example);
    }

    private Wxblqhistory getAverage(List<Wxblqhistory> pthislist) {
        Wxblqhistory pthis = new Wxblqhistory();
        float vref[] = { pthislist.get(0).getVref(), pthislist.get(1).getVref(), pthislist.get(2).getVref(),
                pthislist.get(3).getVref(), pthislist.get(4).getVref(), pthislist.get(5).getVref() };
        float maxvref = HexUtil.MAX(vref);
        float minvref = HexUtil.MIN(vref);
        float sumvref = 0;
        for (int i = 0; i < 6; i++) {
            sumvref += pthislist.get(i).getVref();
        }
        pthis.setVref((sumvref - maxvref - minvref) / 4);

        float acurr[] = { pthislist.get(0).getAcurrent(), pthislist.get(1).getAcurrent(),
                pthislist.get(2).getAcurrent(), pthislist.get(3).getAcurrent(), pthislist.get(4).getAcurrent(),
                pthislist.get(5).getAcurrent() };
        float maxacurr = HexUtil.MAX(acurr);
        float minacurr = HexUtil.MIN(acurr);
        float sumacurr = 0;
        for (int i = 0; i < 6; i++) {
            sumacurr += pthislist.get(i).getAcurrent();
        }
        pthis.setAcurrent((sumacurr - maxacurr - minacurr) / 4);

        float bcurr[] = { pthislist.get(0).getBcurrent(), pthislist.get(1).getBcurrent(),
                pthislist.get(2).getBcurrent(), pthislist.get(3).getBcurrent(), pthislist.get(4).getBcurrent(),
                pthislist.get(5).getBcurrent() };
        float maxbcurr = HexUtil.MAX(bcurr);
        float minbcurr = HexUtil.MIN(bcurr);
        float sumbcurr = 0;
        for (int i = 0; i < 6; i++) {
            sumbcurr += pthislist.get(i).getBcurrent();
        }
        pthis.setBcurrent((sumbcurr - maxbcurr - minbcurr) / 4);

        float ccurr[] = { pthislist.get(0).getCcurrent(), pthislist.get(1).getCcurrent(),
                pthislist.get(2).getCcurrent(), pthislist.get(3).getCcurrent(), pthislist.get(4).getCcurrent(),
                pthislist.get(5).getCcurrent() };
        float maxccurr = HexUtil.MAX(ccurr);
        float minccurr = HexUtil.MIN(ccurr);
        float sumcurr = 0;
        for (int i = 0; i < 6; i++) {
            sumcurr += pthislist.get(i).getCcurrent();
        }
        pthis.setCcurrent((sumcurr - maxccurr - minccurr) / 4);
        return pthis;
    }
    // @Transactional
    // private void AddAndUpdate(Wxblqsensor record) {
    //     int alarmLevel = 0;// 报警等级
    //     String alarmMessage = "";// 报警消息
    //     //报警逻辑
    //     //这里写报警逻辑
    //     //  todo
    //     //  todo
    //     //  todo
    //     record.setLastalarmlevel(alarmLevel);
    //     record.setLastalarmmessage(alarmMessage);
    //     record.setLastcommunicationstatus(0);
    //     record.setLastdatatime(new Date());
    //     record.setLasthisdatatime(addHistory(wxblqsensorServiceImpl.getModel(record)));
    //     if ( wxblqsensorServiceImpl.Update(record, false) == 0) {
    //         setText("更新实时数据失败，请检查数据库连接");
    //     }
    // }
    private Date addHistory(Wxblqsensor sensor){
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp()*1000;
                } else {
                    timersp = ad.getHistimersp()*1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }
    private void add(Wxblqsensor sensor) {
        Wxblqhistory his = new Wxblqhistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setPointname(sensor.getPointname());
        his.setDatatime(sensor.getLastdatatime());
        his.setArescapacity(sensor.getLastarescapacity());
        his.setBrescapacity(sensor.getLastbrescapacity());
        his.setCrescapacity(sensor.getLastcrescapacity());
        his.setCrcurrent(sensor.getLastcrcurrent());
        his.setBrcurrent(sensor.getLastbrcurrent());
        his.setArcurrent(sensor.getLastarcurrent());
        his.setCabsolueangle(sensor.getLastcabsolueangle());
        his.setBabsolueangle(sensor.getLastbabsolueangle());
        his.setAabsolueangle(sensor.getLastaabsolueangle());
        his.setVref(sensor.getLastvref());
        his.setAcurrent(sensor.getLastacurrent());
        his.setBcurrent(sensor.getLastbcurrent());
        his.setCcurrent(sensor.getLastccurrent());
        his.setAangle(sensor.getLastaangle());
        his.setBangle(sensor.getLastbangle());
        his.setCangle(sensor.getLastcangle());
        his.setBatteryvoltage(sensor.getLastbatteryvoltage());
        his.setChargevoltage(sensor.getLastchargevoltage());
        his.setCurrentfrequency(sensor.getLastcurrentfrequency());
        his.setAcurrentgear(sensor.getLastacurrentgear());
        his.setBcurrentgear(sensor.getLastbcurrentgear());
        his.setCcurrentgear(sensor.getLastccurrentgear());
        his.setRefvoltagegear(sensor.getLastrefvoltagegear());
        his.setCurrentvectorsum(sensor.getLastcurrentvectorsum());
        his.setVectorangle(sensor.getLastvectorangle());
        his.setThundertime(sensor.getLastthundertime());
        his.setThundercount(sensor.getLastthundercount());
        his.setThundertimeb(sensor.getLastthundertimeb());
        his.setThundercountb(sensor.getLastthundercountb());
        his.setThundertimec(sensor.getLastthundertimec());
        his.setThundercountc(sensor.getLastthundercountc());
        his.setAcurrentangle(sensor.getLastacurrentangle());
        his.setBcurrentangle(sensor.getLastbcurrentangle());
        his.setCcurrentangle(sensor.getLastccurrentangle());
        his.setAwcurrent(sensor.getLastawcurrent());
        his.setBwcurrent(sensor.getLastbwcurrent());
        his.setCwcurrent(sensor.getLastcwcurrent());
        his.setPtaddr(sensor.getPtaddr());
        his.setAvoltage(sensor.getLastavoltage());
        his.setBvoltage(sensor.getLastbvoltage());
        his.setCvoltage(sensor.getLastcvoltage());
        his.setAvvref(sensor.getAvvref());
        his.setAvacurrent(sensor.getLastavacurrent());
        his.setAvbcurrent(sensor.getLastavbcurrent());
        his.setAvccurrent(sensor.getLastavccurrent());
        his.setSimfrequence(sensor.getSimfrequence());
        his.setAsimxbvoltage(sensor.getAsimxbvoltage());
        his.setAsimxbvoltage1(sensor.getAsimxbvoltage1());
        his.setAsimxbvoltage2(sensor.getAsimxbvoltage2());
        his.setAsimxbvoltage3(sensor.getAsimxbvoltage3());
        his.setBsimxbvoltage(sensor.getBsimxbvoltage());
        his.setBsimxbvoltage1(sensor.getBsimxbvoltage1());
        his.setBsimxbvoltage2(sensor.getBsimxbvoltage2());
        his.setBsimxbvoltage3(sensor.getBsimxbvoltage3());
        his.setCsimxbvoltage(sensor.getCsimxbvoltage());
        his.setCsimxbvoltage1(sensor.getCsimxbvoltage1());
        his.setCsimxbvoltage2(sensor.getCsimxbvoltage2());
        his.setCsimxbvoltage3(sensor.getCsimxbvoltage3());
        his.setPtxishuconfig(sensor.getPtxishuconfig());
        his.setWsdaddr(sensor.getWsdaddr());
        his.setTemperature(sensor.getLasttemperature());
        his.setHumidity(sensor.getLasthumidity());
        his.setMemo(sensor.getMemo());
        his.setInuse(sensor.getInuse());
        his.setStyle(sensor.getStyle());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        wxblqsensorServiceImpl.Add(his);
    }
    private void SensorData(int stationid, int addr, float lastVref, float lastACurrent, float lastBCurrent,
            float lastCCurrent, float lastAAngle, float lastBAngle, float lastCAngle, float lastBatteryVoltage,
            float lastChargeVoltage, float lastCurrentFrequency, float lastACurrentGear, float lastBCurrentGear,
            float lastCCurrentGear, float lastRefVoltageGear, float lastCurrentVectorSum, float lastVectorAngle,
            float lastAcurrentAngle, float lastBcurrentAngle, float lastCcurrentAngle, float lastAWcurrent,
            float lastBWcurrent, float lastCWcurrent) {
        Wxblqsensor nblq = new Wxblqsensor();
        nblq.setDeviceaddr(addr);
        nblq.setStationid(ad.getStationid());
        nblq.setDevicegroup(1);
        nblq.setLastcommunicationstatusBlq(0);
        nblq.setLastdatatime(dt);
        nblq.setLastvref(lastVref);
        nblq.setLastacurrent(lastACurrent);
        nblq.setLastbcurrent(lastBCurrent);
        nblq.setLastccurrent(lastCCurrent);
        nblq.setLastaangle(lastAAngle);
        nblq.setLastbangle(lastBAngle);
        nblq.setLastcangle(lastCAngle);
        nblq.setLastbatteryvoltage(lastBatteryVoltage);
        nblq.setLastchargevoltage(lastChargeVoltage);
        nblq.setLastcurrentfrequency(lastCurrentFrequency);
        nblq.setLastacurrentgear(lastACurrentGear);
        nblq.setLastbcurrentgear(lastBCurrentGear);
        nblq.setLastccurrentgear(lastCCurrentGear);
        nblq.setLastrefvoltagegear(lastRefVoltageGear);
        nblq.setLastcurrentvectorsum(lastCurrentVectorSum);
        nblq.setLastvectorangle(lastVectorAngle);
        nblq.setLastacurrentangle(lastAcurrentAngle);
        nblq.setLastbcurrentangle(lastBcurrentAngle);
        nblq.setLastccurrentangle(lastCcurrentAngle);
        nblq.setLastawcurrent(lastAWcurrent);
        nblq.setLastbwcurrent(lastBWcurrent);
        nblq.setLastcwcurrent(lastCWcurrent);
        if (lastAWcurrent == 0 && lastBWcurrent == 0 && lastCWcurrent == 0)
            return;
        GetBlqAlarm(nblq);
    }

    private void GetBlqAlarm(Wxblqsensor blq) {
        Wxblqsensor alarm = new Wxblqsensor();
        alarm = wxblqsensorServiceImpl.getModel(blq);
        if (alarm == null) {
            setText("当前数据库无监测点：" + blq.getDeviceaddr() + " ！ 请先添加该监测点！");
            return;
        }
        setText("收到数据:addr:" + blq.getDeviceaddr() + "\r\n");
        String str = "解析日新避雷器数据:";
        str = str + " 站点号：" + ad.getStationid();
        str = str + " 设备地址：" + blq.getDeviceaddr();
        str = str + "参考电压：" + blq.getLastvref() + "V\r\n";
        str = str + "A相基波有效值：" + float2(blq.getLastacurrent()) + "mA\r\n";
        str = str + "B相基波有效值：" + float2(blq.getLastbcurrent()) + "mA\r\n";
        str = str + "C相基波有效值：" + float2(blq.getLastccurrent()) + "mA\r\n";
        str = str + "电池电压：" + float2(blq.getLastbatteryvoltage()) + "V\r\n";
        str = str + "充电电压：" + float2(blq.getLastchargevoltage()) + "V\r\n";
        str = str + "A相信号频率：" + float2(blq.getLastcurrentfrequency()) + "Hz\r\n";
        str = str + "A相电流档位：" + float2(blq.getLastacurrentgear()) + "\r\n";
        str = str + "B相电流档位：" + float2(blq.getLastbcurrentgear()) + "\r\n";
        str = str + "C相电流档位：" + float2(blq.getLastccurrentgear()) + "\r\n";
        str = str + "参考相档位：" + float2(blq.getLastrefvoltagegear()) + "\r\n";
        str = str + "电流矢量：" + float2(blq.getLastcurrentvectorsum()) + "mA\r\n";
        str = str + "电流矢量和角度：" + float2(blq.getLastvectorangle()) + "mA\r\n";
        setText(str + "\n");
        str = "电流相角： \r\n" + float2(blq.getLastacurrentangle()) + "度 \r\n";
        str = str + float2(blq.getLastbcurrentangle()) + "度 \r\n";
        str = str + float2(blq.getLastccurrentangle()) + "度 \r\n";
        setText(str + "\n");
        str = "泄漏电流： \r\n" + float2(blq.getLastawcurrent()) + "mA \r\n";
        str = str + float2(blq.getLastbwcurrent()) + "mA \r\n";
        str = str + float2(blq.getLastcwcurrent()) + "mA \r\n";
        setText(str + "\n");
        // 阻性电流

        blq.setLastarcurrent(blq.getLastawcurrent() * 0.1f);
        blq.setLastbrcurrent(blq.getLastbwcurrent() * 0.1f);
        blq.setLastcrcurrent(blq.getLastcwcurrent() * 0.1f);
        str = "阻性电流： \r\n" + float2(blq.getLastawcurrent() * 0.1f) + "mA \r\n";
        str = str + float2(blq.getLastbwcurrent() * 0.1f) + "mA \r\n";
        str = str + float2(blq.getLastcwcurrent() * 0.1f) + "mA \r\n";
        setText(str + "\n");
        int alarmLevel = 0; // 报警等级
        String alarmMessage = "";// '报警消息

        blq.setLastawcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastawcurrent()),
                HexUtil.isnull(alarm.getAwcurrentalarmvalue()),
                HexUtil.isnull(alarm.getAwcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getAwcurrentwarnvalue()),
                HexUtil.isnull(alarm.getAwcurrentwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastawcurrentalarmstatus()), true, "A相全电流",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastbwcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastbwcurrent()),
                HexUtil.isnull(alarm.getBwcurrentalarmvalue()),
                HexUtil.isnull(alarm.getBwcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getBwcurrentwarnvalue()),
                HexUtil.isnull(alarm.getBwcurrentwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastbwcurrentalarmstatus()), true, "B相全电流",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastcwcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastcwcurrent()),
                HexUtil.isnull(alarm.getCwcurrentalarmvalue()),
                HexUtil.isnull(alarm.getCwcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getCwcurrentwarnvalue()),
                HexUtil.isnull(alarm.getCwcurrentwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastcwcurrentalarmstatus()), true, "C相全电流",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastarcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastarcurrent()),
                HexUtil.isnull(alarm.getArcurrentalarmvalue()),
                HexUtil.isnull(alarm.getArcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getArcurrentwarnvalue()),
                HexUtil.isnull(alarm.getArcurrentwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastarcurrentalarmstatus()), true, "A相阻性电流",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastbrcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastbrcurrent()),
                HexUtil.isnull(alarm.getBrcurrentalarmvalue()),
                HexUtil.isnull(alarm.getBrcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getBrcurrentwarnvalue()),
                HexUtil.isnull(alarm.getBrcurrentwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastbrcurrentalarmstatus()), true, "B相阻性电流",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastcrcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastcrcurrent()),
                HexUtil.isnull(alarm.getCrcurrentalarmvalue()),
                HexUtil.isnull(alarm.getCrcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getCrcurrentwarnvalue()),
                HexUtil.isnull(alarm.getCrcurrentwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastcrcurrentalarmstatus()), true, "C相阻性电流",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));
        alarmMessage += GetAlarmMessage(blq.getLastawcurrentalarmstatus(), "全电流A相");
        alarmMessage += GetAlarmMessage(blq.getLastbwcurrentalarmstatus(), "全电流B相");
        alarmMessage += GetAlarmMessage(blq.getLastcwcurrentalarmstatus(), "全电流C相");
        alarmMessage += GetAlarmMessage(blq.getLastarcurrentalarmstatus(), "阻性电流A相");
        alarmMessage += GetAlarmMessage(blq.getLastbrcurrentalarmstatus(), "阻性电流B相");
        alarmMessage += GetAlarmMessage(blq.getLastcrcurrentalarmstatus(), "阻性电流C相");

        alarmLevel = HexUtil.MAX(new int[] { blq.getLastawcurrentalarmstatus(),
                blq.getLastbwcurrentalarmstatus(),
                blq.getLastcwcurrentalarmstatus(),
                blq.getLastarcurrentalarmstatus(),
                blq.getLastbrcurrentalarmstatus(),
                blq.getLastcrcurrentalarmstatus() });
        blq.setLastalarmlevelBlq(alarmLevel);
        blq.setLastalarmmessageBlq(alarmMessage);
        wxblqsensorServiceImpl.Update(blq, false);
    }
    private void lj(String str) {
        int dataStype = 0,status = 0;
        int addr = parseHex4(str.substring(8, 12));
        Wxblqsensor nb = new Wxblqsensor();
        nb.setDeviceaddr(addr);
        nb.setStationid(ad.getStationid());
        nb.setDevicegroup(ad.getDevicegroup());
        nb = wxblqsensorServiceImpl.getModel(nb);
        if (nb == null) {
            setText("当前数据库无避雷器监测点：" + addr + " ！ 请先添加该监测点！");
            return;
        }
        int LastThunderCount = 0, LastThunderCountB = 0, LastThunderCountC = 0;
        Date LastThunderTime = nb.getLastthundertime(), LastThunderTimeB = nb.getLastthundertimeb(),
                LastThunderTimeC = nb.getLastthundertimec();

        switch (str.substring(12, 14)) {
            case "01":
                SensorThunderCountData(nb,ad.getStationid(), addr, new Date(), 1, LastThunderTimeB,
                        LastThunderCountB,
                        LastThunderTimeC, LastThunderCountC, dataStype, status);
                break;
            case "02":
                SensorThunderCountData(nb,ad.getStationid(), addr, LastThunderTime, LastThunderCount, new Date(),
                        1,
                        LastThunderTimeC,
                        LastThunderCountC, dataStype, status);
                break;
            case "03":
                SensorThunderCountData(nb,ad.getStationid(), addr, LastThunderTime, LastThunderCount,
                        LastThunderTimeB,
                        LastThunderCountB, new Date(), 1, dataStype, status);
                break;
        }
    }
        private void SensorThunderCountData(Wxblqsensor nb,int stationid, int addr, Date LastThunderTime, int LastThunderCount,
            Date LastThunderTimeB, int LastThunderCountB, Date LastThunderTimeC, int LastThunderCountC, int dataStype,
            int status) {
                Wxblqsensor nblq = new Wxblqsensor();
        nblq.setDeviceaddr(addr);
        nblq.setDevicegroup(ad.getDevicegroup());
        nblq.setStationid(ad.getStationid());
        nblq.setLastcommunicationstatus(status);
        nblq.setLastdatatime(dt);
        nblq.setLastthundertime(LastThunderTime);
        nblq.setLastthundercount(
                HexUtil.isnull(nb.getLastthundercount()) + LastThunderCount);
        nblq.setLastthundertimeb(LastThunderTimeB);
        nblq.setLastthundercountb(
                HexUtil.isnull(nb.getLastthundercountb()) + LastThunderCountB);
        nblq.setLastthundertimec(LastThunderTimeC);
        nblq.setLastthundercountc(
                HexUtil.isnull(nb.getLastthundercountc()) + LastThunderCountC);
        GetLjAlarm(nblq); // 日新
    }

    private void GetLjAlarm(Wxblqsensor blq) {
        Wxblqsensor alarm = new Wxblqsensor();
        alarm = wxblqsensorServiceImpl.getModel(blq);
        if (alarm == null) {
            setText("当前数据库无监测点：" + blq.getDeviceaddr() + " ！ 请先添加该监测点！");
            return;
        }
        String str;
        str = "解析日新blq雷击时间通信数据：";
        str = str + " 站点号：" + ad.getStationid();
        str = str + " 设备地址：" + blq.getDeviceaddr() + "\r\n";
        str = str + "当前A相雷击次数：" + blq.getLastthundercount() + "\r\n";
        str = str + "当前B相雷击次数：" + blq.getLastthundercountb() + "\r\n";
        str = str + "当前C相雷击次数：" + blq.getLastthundercountc() + "\r\n";
        setText(str + "\r\n");
        int alarmLevel = 0; // 报警等级
        String ljalarmMessage = "";// '报警消息

        blq.setLastthundercountalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastthundercount()),
                HexUtil.isnull(alarm.getThundercountalarmvalue()),
                HexUtil.isnull(alarm.getThundercountalarmrelievevalue()),
                HexUtil.isnull(alarm.getThundercountwarnvalue()),
                HexUtil.isnull(alarm.getThundercountwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastthundercountalarmstatus()), true, "A相雷击次数",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastthundercountbalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastthundercountb()),
                HexUtil.isnull(alarm.getThundercountbalarmvalue()),
                HexUtil.isnull(alarm.getThundercountalarmrelievevalue()),
                HexUtil.isnull(alarm.getThundercountbwarnvalue()),
                HexUtil.isnull(alarm.getThundercountbwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastthundercountbalarmstatus()), true, "B相雷击次数",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLastthundercountcalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastthundercountc()),
                HexUtil.isnull(alarm.getThundercountcalarmvalue()),
                HexUtil.isnull(alarm.getThundercountalarmrelievevalue()),
                HexUtil.isnull(alarm.getThundercountcwarnvalue()),
                HexUtil.isnull(alarm.getThundercountcwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastthundercountcalarmstatus()), true, "C相雷击次数",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));
        ljalarmMessage += GetAlarmMessage(blq.getLastthundercountalarmstatus(), "A相雷击次数");
        ljalarmMessage += GetAlarmMessage(blq.getLastthundercountbalarmstatus(), "B相雷击次数");
        ljalarmMessage += GetAlarmMessage(blq.getLastthundercountcalarmstatus(), "C相雷击次数");

        alarmLevel = HexUtil.MAX(new int[] { blq.getLastthundercountalarmstatus(),
                blq.getLastthundercountbalarmstatus(),
                blq.getLastthundercountcalarmstatus(), });
        blq.setLastalarmlevelLj(alarmLevel);
        blq.setLastalarmmessageLj(ljalarmMessage);
        wxblqsensorServiceImpl.Update(blq, false);
    }
    public void SensorWSDData(int station, int addr, float temPeratrue, float humiDity, int datastype, int status) {
        Wxblqsensor wsddata = new Wxblqsensor();
        wsddata.setDeviceaddr(addr);
        wsddata.setStationid(ad.getStationid());
        wsddata.setDevicegroup(ad.getDevicegroup());
        wsddata = wxblqsensorServiceImpl.getModel(wsddata);
        if (wsddata == null) {
            setText("当前数据库无监测点：" + addr + " ！ 请先添加该监测点！");
            return;
        }
        wsddata.setLasttemperature(temPeratrue);
        wsddata.setLasthumidity(humiDity);
        wsddata.setLastdatatime(dt);

        GetWSDBlqAlarm(wsddata);
    }

    private void GetWSDBlqAlarm(Wxblqsensor blq) {
        Wxblqsensor alarm = new Wxblqsensor();
        alarm = wxblqsensorServiceImpl.getModel(blq);
        if (alarm == null) {
            setText("当前数据库无监测点：" + blq.getDeviceaddr() + " ！ 请先添加该监测点！");
            return;
        }
        String str = "解析温湿度数据" + blq.getDeviceaddr() + ":\r\n";
        str += "温度：" + blq.getLasttemperature() + "度 \r\n";
        str += "湿度：" + blq.getLasthumidity() + "%\r\n";
        setText(str);
        int alarmLevel = 0; // 报警等级
        String alarmMessage = "";// '报警消息

        blq.setLasthumidityalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLasthumidity()),
                HexUtil.isnull(alarm.getHumidityalarmvalue()),
                HexUtil.isnull(alarm.getHumidityalarmrelievevalue()), HexUtil.isnull(alarm.getHumiditywarnvalue()),
                HexUtil.isnull(alarm.getHumiditywarnrelievevalue()),
                HexUtil.isnull(alarm.getLasthumidityalarmstatus()), true, "湿度",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        blq.setLasttemperaturealarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLasttemperature()),
                HexUtil.isnull(alarm.getTemperaturealarmvalue()),
                HexUtil.isnull(alarm.getTemperaturealarmrelievevalue()),
                HexUtil.isnull(alarm.getTemperaturewarnvalue()), HexUtil.isnull(alarm.getTemperaturewarnrelievevalue()),
                HexUtil.isnull(alarm.getLasttemperaturealarmstatus()), true, "温度",alarm.getDevicegroup(), alarm.getDeviceaddr(),
                alarm.getPointname()));

        alarmMessage += GetAlarmMessage(blq.getLasttemperaturealarmstatus(), "温度");
        alarmMessage += GetAlarmMessage(blq.getLasthumidityalarmstatus(), "湿度");

        alarmLevel = HexUtil.MAX(new int[] { blq.getLasthumidityalarmstatus(), blq.getLasttemperaturealarmstatus() });
        blq.setLastalarmlevelWsd(alarmLevel);
        blq.setLastcommunicationstatusWsd(0);
        blq.setLastalarmmessageWsd(alarmMessage);
        blq.setDeviceaddr(null);
        Example example = new Example(Wxblqsensor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", blq.getStationid());
        criteria.andEqualTo("devicegroup", blq.getDevicegroup());
        criteria.andEqualTo("inuse", blq.getInuse());
        criteria.andEqualTo("wsdaddr", blq.getWsdaddr());
        wxblqsensorServiceImpl.updateByExampleSelective(blq, example);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {

        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if(isAvailable()){
                    numindex++;
                    // if(numindex*timersp>300*1000)
                    // {
                    //         nextstep = BRO;   
                    //         numindex = 0;   
                                              
                    // }
                    switch (nextstep) {

                        case DELAY5: 
                        if(numindex*timersp>300*1000)
                        {
                                nextstep = BRO;   
                                numindex = 0;   
                                                  
                        }
                        break;  
                        case BRO:                  
                        addrindex++;
                        if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                            addrindex = Appdevice.getAddrmin();
                            sender = new Wxblqsensor();
                            sender.setDeviceaddr(addrindex);
                            sender.setDevicegroup(ad.getDevicegroup());
                            sender.setStationid(ad.getStationid());
                            sender = wxblqsensorServiceImpl.getModel(sender);
                            if (sender == null) {
                                setText("无线避雷器地址" + addrindex + "与用户所设定的地址对应不上");
                                continue;
                            }
                            sender.setLastcommunicationstatus(HexUtil.MAX(new int[] {
                                    HexUtil.isnull(sender.getLastcommunicationstatusBlq()),
                                    sender.getWsdaddr() == null ? 0
                                            : HexUtil.isnull(sender.getLastcommunicationstatusWsd()),
                                    sender.getPtaddr() == null ? 0
                                            : HexUtil.isnull(sender.getLastcommunicationstatusPt())
                            }));
                            sender.setLastalarmlevel(HexUtil.MAX(new int[] {
                                HexUtil.isnull(sender.getLastalarmlevelBlq()),
                                HexUtil.isnull(sender.getLastalarmlevelLj()),
                                sender.getWsdaddr() == null ? 0
                                        : HexUtil.isnull(sender.getLastalarmlevelWsd()),
                                sender.getPtaddr() == null ? 0
                                        : HexUtil.isnull(sender.getLastalarmlevelPt())
                            }));
                            String ptmsg = "",wsdmsg = "";
                            if(sender.getWsdaddr() != null)
                                wsdmsg = isnull(sender.getLastalarmmessageWsd());
                            if(sender.getPtaddr() != null)
                                ptmsg = isnull(sender.getLastalarmmessagePt());
                            String almmsg = isnull(sender.getLastalarmmessageBlq())+isnull(sender.getLastalarmmessageLj());
                            sender.setLastalarmmessage(almmsg+wsdmsg+ptmsg);
                            wxblqsensorServiceImpl.Update(sender, false);
                            currblqaddr = addrindex;

                            if (sender.getPtaddr() != null && sender.getPtaddr() > 3000) {
                                pt = ON;
                            } else {
                                pt = OFF;
                            }
                            if (sender.getWsdaddr() != null && sender.getWsdaddr() >= 0) {
                                wsd = ON;
                            } else {
                                wsd = OFF;
                            }
                            cstr = String.format("FEAA08A9%s", HexUtil.intToHexString(addrindex, 2));
                            cstr = cstr + CRC16.calcCrc16(cstr);
                            try {
                                Send(cstr);
                            } catch (Exception EX) {
                                setText(EX.toString());
                            }
                            setText("向无线避雷器" + currblqaddr + "设备发送命令" + cstr);
                           
                        //if(numindex*timersp>300*1000)
                            {
                                    nextstep = BLQ;   
                                   
                                                      
                            }

                            break;  
                        
                    case BLQ:
                    {

                        if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                            addrindex = Appdevice.getAddrmin();
                        
                            cstr = String.format("FEAA08A6%s", HexUtil.intToHexString(addrindex, 2));
                            cstr = cstr + CRC16.calcCrc16(cstr);
                            try {
                                Send(cstr);
                            } catch (Exception EX) {
                                setText(EX.toString());
                            }
                            setText("向无线避雷器" + addrindex + "设备发送指令" + cstr);
                            BLQReSend[currblqaddr]++;
                            // if (BLQReSend[currblqaddr] > 3) {
                            //     wxblqsensorServiceImpl.UpdateStatus(ad, addrindex, 1, "blq");
                            //     setText("无线避雷器设备端口通讯异常...请检查原因");
                                 nextstep = BRO;
                            // }                         
                            numindex = 0;   
                        break;
                    }
                    case PT: 
                    cstr = String.format("FEAA08A6%s", HexUtil.intToHexString(sender.getPtaddr(), 2));
                    cstr = cstr + CRC16.calcCrc16(cstr);
                    try {
                        Send(cstr);
                    } catch (Exception EX) {
                        setText(EX.toString());
                    }
                    setText("向无线避雷器" + currblqaddr + "的母线" + sender.getPtaddr() + "设备发送指令" + cstr);
                    PtReSend[currblqaddr]++;
                    if (PtReSend[currblqaddr] > 3) {
                        wxblqsensorServiceImpl.UpdateStatus(ad, addrindex, 1, "pt");
                        setText("无线避雷器设备端口通讯异常...请检查原因");

                    if (wsd)
                        nextstep = WSD;
                    else
                        nextstep = BLQ;
                    }                                   
                    break;

                    case WSD:
                    // 温湿度
                    cstr = String.format("%s0400010002",
                            HexUtil.intToHexString(sender.getWsdaddr(), 1));
                    cstr = cstr + CRC16.calcCrc16(cstr);
                    try {
                        Send(cstr);
                    } catch (Exception EX) {
                        setText(EX.toString());
                    }
                    setText("向无线避雷器" + currblqaddr + "的温湿度" + sender.getWsdaddr() + "设备发送指令" + cstr);
                    WSDReSend[currblqaddr]++;
                    if (WSDReSend[currblqaddr] > 3) {
                        wxblqsensorServiceImpl.UpdateStatus(ad, addrindex, 1, "wsd");
                        setText("无线避雷器设备端口通讯异常...请检查原因");
                        nextstep = BLQ;
                    }
                    break;


                    }
                }else if (rescode != 0) {
                    setText(resmsg[rescode]);
                }
            }
            Thread.sleep(timersp);
        }
    }


}
